package com.sgb.kjwl.view.ui.adapter.self.carMasters;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.makeramen.roundedimageview.RoundedImageView;
import com.sgb.kjwl.BR;
import com.sgb.kjwl.R;
import com.sgb.kjwl.model.entity.self.BusinessSubscribeEntity;
import com.sgb.kjwl.utils.CargoConstant;
import com.sgb.kjwl.utils.LonLatUtils;
import com.sgb.kjwl.utils.NumberUtil;
import com.sgb.kjwl.utils.VehicleConstant;
import com.sgb.kjwl.view.ui.activity.self.userInfo.VerificationCodeLoginActivity;
import com.sgb.kjwl.view.widget.CenteredImageSpan;
import com.swgk.core.dialog.RoundCornerDialog;
import com.swgk.core.recyclerview.adapter.BaseRecycleAdapter;
import com.swgk.core.recyclerview.adapter.ItemViewHolder;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.util.StringUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Describe:
 * Author:  yangLei
 * Date:    2021/4/6
 */
public class SourceSubscriptionAdapter extends BaseRecycleAdapter<BusinessSubscribeEntity> {
    private Context mContext;
    private List<BusinessSubscribeEntity> data;

    public SourceSubscriptionAdapter(Context context, List<BusinessSubscribeEntity> datas) {
        super(context, R.layout.sub_item_goods_info, datas);
        mContext = context;
        this.data = datas;
    }

    public List<BusinessSubscribeEntity> getData() {
        if (data == null)
            data = new ArrayList<>();
        return data;
    }

    @Override
    public void convert(ItemViewHolder holder, BusinessSubscribeEntity entity) {
        holder.setBinding(BR.viewModel, entity);
        TextView tv_city = holder.getView(R.id.tv_city);
        TextView tv_distance = holder.getView(R.id.tv_distance);
        TextView type_name = holder.getView(R.id.type_name);
        TextView price_view = holder.getView(R.id.price_view);
        TextView content_view = holder.getView(R.id.content_view);
        TextView tv_company = holder.getView(R.id.tv_company);
        TextView tv_journey = holder.getView(R.id.transport_distance);
        TextView load_time = holder.getView(R.id.load_time);
        TextView role = holder.getView(R.id.role);
        RoundedImageView iv_logo = holder.itemView.findViewById(R.id.iv_logo);

        //整车/零担
        ImageView loadType = holder.itemView.findViewById(R.id.load_type);
        String loadTypeStr = CargoConstant.getTransportTypeStr(entity.getTransportType());
        // 一口价/电议
        if (null!=entity.getFreightType()&&entity.getFreightType() == 1) {
            price_view.setText(String.format("%s %s", mContext.getResources().getString(R.string.app_the_freight_combined), "电议"));
        } else {
            price_view.setText(!entity.getAllFreight().isEmpty() ? mContext.getResources().getString(R.string.app_the_freight_combined) + " " + NumberUtil.trim0(entity.getAllFreight()) + "元" : "");
        }
       /* //装货时间调整 2.0.6
        StringBuilder loadTime = new StringBuilder();
        if (entity.getShipmentTime() > 0) {
            loadTime.append(CargoConstant.stampFormatLoadText(entity.getShipmentTime(), entity.getStartPointTime()));
            if (entity.getShipmentEndTime() > 0 && entity.getShipmentEndTime() != entity.getShipmentTime()) {
                loadTime.append("-" + CargoConstant.stampFormatLoadText(entity.getShipmentEndTime(), entity.getEndPointTime()));
            }
        } else if (entity.getShipmentEndTime() > 0) {
            loadTime.append(CargoConstant.stampFormatLoadText(entity.getShipmentEndTime(), entity.getEndPointTime()));
        }
        if (loadTime.toString().length() > 0) {
            load_time.setVisibility(View.VISIBLE);
            load_time.setText(loadTime.append("装货").toString());
        } else {
            load_time.setVisibility(View.GONE);
        }*/
        //装货时间调整
        String loadTime = CargoConstant.stampFormatListLoadTime(
                entity.getShipmentTime(), entity.getStartPointTime(),
                entity.getShipmentEndTime(), entity.getEndPointTime());
        if (!TextUtils.isEmpty(loadTime)) {
            load_time.setText(loadTime + "装货");
        } else {
            load_time.setVisibility(View.GONE);
        }

        String addStr = "";
        if (!TextUtils.isEmpty(entity.getCityName())) {
            addStr += entity.getCityName() + " ";
        }
        if (!TextUtils.isEmpty(entity.getDistrictName())) {
            addStr += entity.getDistrictName() + " ";
        }
        addStr += " ➞ ";
        if (!TextUtils.isEmpty(entity.getDestCityName())) {
            addStr += entity.getDestCityName() + " ";
        }
        if (!TextUtils.isEmpty(entity.getDestDistrictName())) {
            addStr += entity.getDestDistrictName();
        }
        addStr += "   ";
        if (!TextUtils.isEmpty(entity.getPattern()) && entity.getPattern().equals("1")) {
            content_view.setText(TextUtils.isEmpty(entity.getOfferType())?"":entity.getOfferTypeWorlds()+" 可报价");
            //竞价货源
            Drawable drawable = mContext.getResources().getDrawable(R.drawable.icon_jingjia);
            drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
            CenteredImageSpan imgSpan = new CenteredImageSpan(drawable);
            SpannableString spannableString = new SpannableString(addStr);
            spannableString.setSpan(imgSpan, spannableString.length() - 1, spannableString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            tv_city.setText(spannableString);
        } else {
            //普通货源
            tv_city.setText(addStr.trim());
            String carModelNameStr = TextUtils.isEmpty(entity.getCarTypeName()) ? "" : entity.getCarTypeName().replace(",", "/").trim() + " ";
            String carLenStr = TextUtils.isEmpty(entity.getCarLenName()) ? "" : entity.getCarLenName().replace(",", "/").trim() + " ";
            String heightHurdleStr = getValidHeightHurdle(entity.getHeightHurdle()).replace(",", "/").trim() + " ";
            String dumpStr = TextUtils.isEmpty(VehicleConstant.getIsDumpStr(entity.getIsDump())) ? "" : VehicleConstant.getIsDumpStr(entity.getIsDump());
            String carInfo = carModelNameStr + carLenStr + heightHurdleStr + dumpStr;
            content_view.setText(StringUtil.removeChar(carInfo, "/"));
        }


        double distance = 0.0d;
        if (!TextUtils.isEmpty(entity.getLongitude()) && !TextUtils.isEmpty(entity.getLatitude())) {
            distance = LonLatUtils.getDistance(Double.parseDouble(entity.getLongitude()), Double.parseDouble(entity.getLatitude()), NumberUtil.convertToDouble(SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LONGITUDE_ID, "")), NumberUtil.convertToDouble(SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LATITUDE_ID, "")));
        }
        if (distance <= 0) {
            tv_distance.setText("");
        } else {
            tv_distance.setText("距您 " + (distance < 1 ? "1km以内" : StringUtil.formatUpDistance(String.valueOf(distance)) + "km"));
        }

        String modelStr = TextUtils.isEmpty(entity.getGoodsModelName()) ? "" : CargoConstant.getLastGoodsTypeName(entity.getGoodsModelName(), entity.getSecondGoodsTypeName());
        String wightStr = TextUtils.isEmpty(entity.getWeight()) ? "" : "/" + NumberUtil.trim0(entity.getWeight()) + "吨";
        String volumeStr = TextUtils.isEmpty(entity.getVolume()) ? "" : "/" + NumberUtil.trim0(entity.getVolume()) + "方";
        type_name.setText(modelStr + wightStr + volumeStr);

        tv_company.setText(entity.getCompanyName());
    if (!TextUtils.isEmpty(entity.getPattern()) && entity.getPattern().equals("1")){
//        tv_journey.setVisibility(View.GONE);
        loadType.setVisibility(View.GONE);
    }else {
        if (loadTypeStr.equals("零担")) {
            loadType.setVisibility(View.VISIBLE);
            loadType.setImageResource(R.drawable.icon_less_than_tag);
        } else if (loadTypeStr.equals("整车")) {
            loadType.setVisibility(View.VISIBLE);
            loadType.setImageResource(R.drawable.icon_carload_tag);
        } else {
            loadType.setVisibility(View.GONE);
        }
    }
        if (TextUtils.isEmpty(entity.getJourney())) {
            tv_journey.setText("");
            tv_journey.setVisibility(View.GONE);
        } else {
            String journey = Double.valueOf(entity.getJourney()) < 1000 ? "1km以内" : StringUtil.fromatUpDistance(entity.getJourney()) + "km";
            tv_journey.setText("运程 " + journey);
            tv_journey.setVisibility(View.VISIBLE);
        }
        if (!TextUtils.isEmpty(entity.getTerminal())) {
            //头像
            if (!TextUtils.isEmpty(entity.getLogo())) {
                RequestOptions options = new RequestOptions()
                        .dontAnimate()
                        .placeholder(entity.getTerminal() != null ? entity.getTerminal().equals("3") ? R.drawable.geren_person_touxiang : entity.getTerminal().equals("1") ? R.mipmap.goods_list_company_icon : R.drawable.goods_detail_touxiang : R.drawable.goods_detail_touxiang)
                        .error(entity.getTerminal() != null ? entity.getTerminal().equals("3") ? R.drawable.geren_person_touxiang : entity.getTerminal().equals("1") ? R.mipmap.goods_list_company_icon : R.drawable.goods_detail_touxiang : R.drawable.goods_detail_touxiang)
                        .centerCrop();
                Glide.with(context).load(entity.getLogo()).apply(options).into(iv_logo);
            } else {
                iv_logo.setImageResource(entity.getTerminal() != null ? entity.getTerminal().equals("3") ? R.drawable.geren_person_touxiang : entity.getTerminal().equals("1") ? R.mipmap.goods_list_company_icon : R.drawable.goods_detail_touxiang : R.drawable.goods_detail_touxiang);
            }

            role.setVisibility(View.VISIBLE);
            //企业/个人/团队  都取CompanyName的值
            switch (entity.getTerminal()) {
                case "1":
                    role.setBackgroundResource(R.drawable.bg_blue_solid_ring);
                    role.setTextColor(Color.parseColor("#5792FD"));
                    role.setText("企业");
                    if (!TextUtils.isEmpty(entity.getCompanyName()))
                        tv_company.setText(entity.getCompanyName());
                    iv_logo.setOval(false);
                    iv_logo.setCornerRadius(4);
                    break;
                case "2":
                    role.setBackgroundResource(R.drawable.bg_green_ring);
                    role.setText("中介");
                    role.setTextColor(Color.parseColor("#06C764"));
                    if (!TextUtils.isEmpty(entity.getCompanyName()))
                        tv_company.setText(entity.getCompanyName());
                    iv_logo.setOval(true);
                    break;

                //个人不展示
                case "3":
                    role.setBackgroundResource(R.drawable.bg_orange_ring);
                    role.setText("个人");
                    role.setTextColor(Color.parseColor("#FFC000"));
                    role.setVisibility(View.GONE);
                    if (!TextUtils.isEmpty(entity.getCompanyName()))
                        tv_company.setText(entity.getCompanyName());
                    iv_logo.setOval(true);
                    break;

            }
        } else {
            role.setVisibility(View.GONE);
        }

/*        if (!TextUtils.isEmpty(entity.getLogo())) {
            Glide.with(context).load(entity.getLogo()).into(iv_logo);
        }
        if (!TextUtils.isEmpty(entity.getTerminal())) {
            role.setVisibility(View.VISIBLE);
            switch (entity.getTerminal()) {
                case "1":
                    role.setBackgroundResource(R.drawable.bg_blue_solid_ring);
                    role.setTextColor(Color.parseColor("#5792FD"));
                    role.setText("货主");
                    iv_logo.setOval(false);
                    iv_logo.setCornerRadius(4);
                    break;
                case "2":
                    role.setBackgroundResource(R.drawable.bg_green_ring);
                    role.setText("中介");
                    role.setTextColor(Color.parseColor("#06C764"));
                    iv_logo.setOval(true);
                    break;
                case "3":
                    role.setBackgroundResource(R.drawable.bg_orange_ring);
                    role.setText("个人");
                    role.setTextColor(Color.parseColor("#FFC000"));
                    role.setVisibility(View.GONE);
                    iv_logo.setOval(true);
                    break;

            }
        } else {
            role.setVisibility(View.GONE);
        }*/

        holder.getView(R.id.call_phone).setOnClickListener(v -> callPhone(entity));
    }


    private String getValidHeightHurdle(String heightHurdle) {
        if (TextUtils.isEmpty(heightHurdle) || heightHurdle.equals("0.0")) {
            return "";
        }
        return " 栏高 " + NumberUtil.trim0(heightHurdle) + "米";
    }

    private void callPhone(BusinessSubscribeEntity entity) {
        if (!isLogin()) {
            VerificationCodeLoginActivity.start(mContext);
            return;
        }
        if (!TextUtils.isEmpty(entity.getContrctsNumber()))
            showDialog(entity.getContrctsNumber());
        else
            MToast.showLongToast(mContext, "无联系方式");
    }


    /**
     * 拨打电话对话框
     *
     * @param phone
     */
    private void showDialog(String phone) {
        View view = View.inflate(mContext, R.layout.dialog_two_btn, null);
        final RoundCornerDialog roundCornerDialog = new RoundCornerDialog(mContext, 0, 0, view, R.style.RoundCornerDialog);
        roundCornerDialog.show();
        roundCornerDialog.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失

        TextView tv_message = view.findViewById(R.id.tv_message);
        TextView tv_title = view.findViewById(R.id.tv_title);
        TextView tv_logout_confirm = view.findViewById(R.id.tv_logout_confirm);
        TextView tv_logout_cancel = view.findViewById(R.id.tv_logout_cancel);
        tv_title.setText("确认呼叫");
        tv_title.setVisibility(View.VISIBLE);
        tv_message.setText(phone);
        tv_logout_confirm.setText("拨打");
        //确定
        tv_logout_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(Intent.ACTION_DIAL);
                Uri data = Uri.parse("tel:" + phone);
                intent.setData(data);
                mContext.startActivity(intent);
                roundCornerDialog.dismiss();

            }
        });
        //取消
        tv_logout_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                roundCornerDialog.dismiss();
            }
        });
    }

    private boolean isLogin() {
        return !TextUtils.isEmpty(SharedPreferenceUtil.getInstance().
                getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""));
    }

}
